<template>
  <view>
    <view
      class="player-item"
      v-for="(player, index) in playerList"
      :key="index"
    >
      <image :src="getOneFromCover(player.cover)" class="player-img" />
      <view class="player-info">
        <view class="player-header">
          <view class="player-name">
            {{ player.tittle }}
            <uni-tag
              :text="`${index + 1}号选手`"
              type="primary"
              size="small"
              :inverted="true"
            />
          </view>
          <text class="player-vote-num">{{ player.num }}票</text>
        </view>
        <text class="player-desc">{{ player.intro }}</text>
        <view class="player-btn-container">
          <button
            class="player-btn"
            type="primary"
            size="mini"
            @tap="playerEdit(index)"
          >
            编辑
          </button>
          <button
            class="player-btn"
            type="warn"
            size="mini"
            @tap="playerDelete(player)"
          >
            移除
          </button>
        </view>
      </view>
    </view>
    <button class="add-player-btn" @click="toggle()">添加选手</button>
    <view>
      <!-- 普通弹窗 -->
      <uni-popup ref="playerPopup" background-color="#fff" type="bottom">
        <view class="player-container">
          <uni-forms ref="playerRef" :model="playerForm" :rules="playerRules">
            <uni-forms-item name="images">
              <uni-file-picker
                limit="1"
                title="最多选择1张图片"
                fileMediatype="image"
                @select="playerImageSelect"
                @delete="playerImagesDelete"
                v-model="playerForm.images"
                return-type="array"
              ></uni-file-picker>
            </uni-forms-item>
            <uni-forms-item label="选手名称:" name="tittle" label-width="85">
              <uni-easyinput
                type="text"
                v-model="playerForm.tittle"
                placeholder="请输入投票标题"
              ></uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="选手描述:" name="intro" label-width="85">
              <uni-easyinput
                type="textarea"
                v-model="playerForm.intro"
                placeholder="请输入选手描述"
              ></uni-easyinput>
            </uni-forms-item>
            <view class="form-btn-container">
              <button @click="playerSubmit" class="submit-btn">
                {{ isEdit ? "修改" : "添加" }}选手
              </button>
            </view>
          </uni-forms>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  playerParamsType,
  playerResponseType,
  PublishState,
  addPlayerType,
  imageType,
} from "@/types/vote";
import {
  getPlayerListAPI,
  addPlayerAPI,
  updatePlayerAPI,
  deletePlayerAPI,
} from "@/api/player";
import { handleCoverToImageList, getOneFromCover } from "@/utils/vote";
import { uploadFileAPI } from "@/api/file";

onLoad(async () => {
  await getPlayerList();
});

// 接收页面参数
const query = defineProps<{
  id: string;
}>();

const pageParams: playerParamsType = reactive({
  actId: query.id,
  page: 1,
  size: 999,
  state: PublishState.approved,
  tittle: "",
});

const playerList = ref<playerResponseType[]>([]);

const isEdit = ref(false);
const playerIndex = ref(0);

const playerPopup = ref<UniHelper.UniPopupInstance>();

//选手表单
const playerForm: addPlayerType = reactive({
  images: [],
  tittle: "",
  intro: "",
  cover: "",
  state: PublishState.approved,
  actId: query.id,
});

const playerRules: UniHelper.UniFormsRules = {
  images: {
    rules: [{ required: true, errorMessage: "请上传选手图片" }],
  },
  tittle: {
    rules: [
      { required: true, errorMessage: "请输入选手名称" },
      { maxLength: 16, errorMessage: "选手名称不能超过16个字符" },
    ],
  },
  intro: {
    rules: [
      {
        required: true,
        errorMessage: "请输入选手描述",
      },
      { maxLength: 100, errorMessage: "选手描述不能超过100个字符" },
    ],
  },
};
const playerRef = ref<UniHelper.UniFormsInstance>();

// 获取选手列表
const getPlayerList = async (searchValue: string = "") => {
  pageParams.tittle = searchValue;
  const res = await getPlayerListAPI(pageParams);
  playerList.value = res.data.records;
};

//打开添加弹窗
const toggle = () => {
  isEdit.value = false;
  resetPlayerForm();
  playerPopup.value?.open?.();
};

//重置选手表单
const resetPlayerForm = () => {
  playerForm.id = "";
  playerForm.images = [];
  playerForm.tittle = "";
  playerForm.intro = "";
  playerForm.cover = "";
};

//选手
const playerImageSelect: UniHelper.UniFilePickerOnSelect = (event: any) => {
  const imageDatas = event.tempFiles.map((item: any) => {
    return { url: item.url, name: item.name };
  });
  playerForm.images.push(...imageDatas);
};

const playerImagesDelete: UniHelper.UniFilePickerOnDelete = (event: any) => {
  playerForm.images.splice(event.index, 1);
};

const playerSubmit = async () => {
  await playerRef.value?.validate?.();
  if (isEdit.value) {
    if (playerForm.images[0].url !== playerForm.cover) {
      await playerUploadFile(playerForm.images);
    }
    await updatePlayerAPI(playerForm);
    uni.showToast({
      title: "修改选手成功",
      icon: "success",
      duration: 1000,
    });
    await getPlayerList(pageParams.tittle);
  } else {
    await playerUploadFile(playerForm.images);
    await addPlayerAPI(playerForm);
    uni.showToast({
      title: "添加选手成功",
      icon: "success",
      duration: 1000,
    });
    await getPlayerList(pageParams.tittle);
  }
  playerPopup.value?.close?.();
};

const playerUploadFile = async (imageList: imageType[]) => {
  const uploadPromises = imageList.map((item) => uploadFileAPI(item));
  try {
    const responses = await Promise.all(uploadPromises);
    const fileUrlList = responses.flatMap((res) => res.data.fileUrl);
    playerForm.cover = fileUrlList.join(","); // 使用 join 代替 toString
  } catch (error) {
    console.error("上传文件时发生错误：", error);
    // 处理错误的逻辑，比如显示提示信息等
  }
};

//编辑选手
const playerEdit = (index: number) => {
  isEdit.value = true;
  playerIndex.value = index;
  playerForm.images = handleCoverToImageList(playerList.value[index].cover);
  playerForm.id = playerList.value[index].id;
  playerForm.tittle = playerList.value[index].tittle;
  playerForm.intro = playerList.value[index].intro;
  playerForm.cover = playerList.value[index].cover;
  playerPopup.value?.open?.();
};

//删除选手
const playerDelete = (item: playerResponseType) => {
  //是否投票某选手提示弹窗
  uni.showModal({
    title: "删除提示",
    content: `是否删除选手【${item.tittle}】？`,
    success: async function (res) {
      if (res.confirm) {
        await deletePlayerAPI(item.id);
        uni.showToast({
          title: "删除成功",
          icon: "success",
          duration: 1000,
        });
        getPlayerList();
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

defineExpose({ getPlayerList });
</script>
<style scoped lang="scss">
.player-item {
  display: flex;
  margin: 10rpx 0;
  padding: 20rpx;
  border-radius: 12rpx;
  background-color: #fff;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  .player-img {
    width: 200rpx;
    height: 200rpx;
  }
  .player-info {
    flex-grow: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .player-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .player-name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
      .player-vote-num {
        font-size: 26rpx;
        color: #333;
      }
    }
    .player-desc {
      font-size: 24rpx;
      color: #666;
    }
    .player-btn-container {
      display: flex;
      justify-content: flex-end;
      .player-btn {
        margin: 0 10rpx;
      }
    }
  }
}

.add-player-btn {
  width: 500rpx;
  background-color: #2979ff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 10rpx;
  margin: 20rpx auto 0;
  cursor: pointer;
  text-align: center;
}

.player-container {
  padding: 20px;
  .form-btn-container {
    display: flex;
    justify-content: space-between;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 500rpx;
      background-color: #2979ff;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
      color: #fff;
    }
  }
}
</style>
